/**
 * Created by john on 2016/3/12.
 */
/**
 * Created by john on 2016/3/12.
 */
$(function () {
    var add = {
        actId: null,
        isNewAct: true,
        tplData: {},
        inputParams: null,
        inputClass: new Array(),
        init: function () {
            var that = this;
            that.formatDate();
            that.actId = that.getParamFromUrl('activityId');
            if (that.actId) {
                $.ajax({
                    url: absoluteContextPath + "/activity/getActivityAndFlows",
                    type: 'POST',
                    data: {
                        activityId: parseInt(that.actId),
                        page: 1,
                        size: 1000
                    },
                    beforeSend: function (request) {
                        request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
                    },
                    success: function (res) {
                        that.isNewAct = false;
                        that.tplData = res.data;
                        that.tplData.isNewAct = false;
                        that.renderPage();
                        that.initPlugin();
                    }
                });
            }
            else {
                that.tplData.isNewAct = true;
                that.renderPage();
                that.initPlugin();
            }
            $(".js_close_btn").click(function () {
                $(this).parent().parent().toggleClass('fade').toggleClass('hide');
            })

        },

        getParamFromUrl: function (str) {
            var q = window.location.search.substr(1);
            var qs = q.split("&");
            if (qs) {
                for (var i = 0; i < qs.length; i++) {
                    var key = qs[i].substring(0, qs[i].indexOf("="));
                    if (key == str) {
                        return qs[i].substring(qs[i].indexOf("=") + 1);
                    }
                }
            }
        },

        renderPage: function () {
            var rule;
            if (!this.isNewAct) {
                rule = this.tplData.activity.rule;

            }
            else {
                rule = {};
            }

            $("#js_page").html(template("pageTpl", this.tplData));
            if (console) {
                console.log("data:%o", this.tplData);
            }
            if (!this.isNewAct) {
                $("#logo_img").attr("src", this.tplData.activity.logoUrl);
                $(".js_create_btn").html("保存修改");
                $("#myModalLabel").html("修改成功");
                $("#activityLink").html(this.tplData.activity.link);
                $("#exchangeLink").html(this.tplData.activity.exchangeLink);
                if (this.tplData.list) {
                    for (var i = 0; i < this.tplData.list.length; i++) {
                        var _f = this.tplData.list[i];
                        var _t = _f["carrier"];
                        _tpl = $("tr td[data-what='" + _t + "']").find("li[data-tpl='true']").clone();
                        _tpl.find("span").html(_f["name"]);
                        _tpl.find("input[type='text']").val(_f["probability"]);
                        _tpl.find("input[type='hidden']").val(_f["flowId"]);
                        _tpl.removeAttr("data-tpl");
                        $("tr td[data-what='" + _t + "']").append(_tpl);
                    }

                }

                $("#linkBox").show(300);
            }
            $("#rule").html(rule);
            this.bindNextBtn();
        },

        initPlugin: function () {
            $(".form_datetime").datetimepicker({
                format: "yyyy-mm-dd hh:ii:ss",
                autoclose: true,
                todayBtn: true
            });

            var editor = new Simditor({
                textarea: $('#rule')
            });
            if (!this.isNewAct) {
                $("#startTime").attr('value', (new Date(this.tplData.activity.startTime)).format('yyyy-MM-dd hh:mm:ss'));
                $("#endTime").attr('value', (new Date(this.tplData.activity.endTime)).format('yyyy-MM-dd hh:mm:ss'));
            }
        },

        formatDate: function () {
            Date.prototype.format = function (time) {
                var o = {
                    "M+": this.getMonth() + 1,
                    "d+": this.getDate(),
                    "h+": this.getHours(),
                    "m+": this.getMinutes(),
                    "s+": this.getSeconds(),
                    "q+": Math.floor((this.getMonth() + 3) / 3),
                    "S": this.getMilliseconds()
                };
                if (/(y+)/.test(time)) {
                    time = time.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
                }
                for (var k in o) {
                    if (new RegExp("(" + k + ")").test(time)) {
                        time = time.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
                    }
                }
                return time;
            };

        },
        bindNextBtn: function () {
            var that = this;
            $(".js_next_step_btn").unbind('click').bind('click', function () {
                that.inputParams = {
                    title: $("#title").val(),
                    count: parseInt($("#count").val()),
                    startTime: Date.parse(new Date($("#startTime").val())),
                    endTime: Date.parse(new Date($("#endTime").val())),
                    rule: $("#rule").val(),
                    logoUrl: $("#logo_img").attr('src')
                };
                if (!that.isNewAct) {
                    that.inputParams.id = that.actId;


                }
                var isAllFill = true;
                _.each(that.inputParams, function (value, key) {
                    if (!value) {
                        isAllFill = false;
                    }
                });
                if (isAllFill) {
                    $("#baseForm").hide(500);
                    $("#flowForm").show(500);
                    $("#stepNav").find('li').eq(0).removeClass('active');
                    $("#stepNav").find('li').eq(1).addClass('active');
                    that.bindAddBtn();
                }
                else {
                    alert('请将活动信息填写完整!');
                }

                $("input[data-what]").each(function () {
                    $(this).click();
                });
            });
        },

        bindAddBtn: function () {
            var $addBtn = $(".js_add_btn");
            var that = this;
            $addBtn.unbind('click').bind('click', function () {
                var carrier = $(this).attr('data-what');
                var index = $addBtn.index($(this));
                var $this = $(this);
                //$(".pb-item").not("[data-tpl]").remove();
                $(".select-item").remove();
                $.ajax({
                    url: absoluteContextPath + "/activity/flowList",
                    type: 'POST',
                    data: {
                        carrier: carrier
                    },
                    beforeSend: function (request) {
                        request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
                    },
                    success: function (res) {
                        console.log('res');
                        if (res.result == 0) {
                            console.log(res.data);
                            //显示浮层
                            //that.showFlowSelectBox(res.data.list, carrier);
                            //请求到的数据显示出来
                            var $container = $(".table").find('td').eq(index).find('.flow-list');
                            var uniqueId = _.uniqueId();
                            that.inputClass.push(".flow-input-" + uniqueId);
                            _.each(res.data.list, function (value, index) {
                                if (!that.isNewAct && $(".pb-item").find('input[type="hidden"][value=' + value.id + ']').length > 0) {
                                    $container.append("<li class='select-item'><button data-for='" + carrier + "' data-flow-id='" + value.id + "' class='flow-input-" + uniqueId + " sld' type='button'  class='btn btn-primary'>" + value.name + "</button></li>");
                                } else {
                                    $container.append("<li class='select-item'><button data-for='" + carrier + "' data-flow-id='" + value.id + "' class='flow-input-" + uniqueId + "' type='button'  class='btn btn-primary'>" + value.name + "</button></li>");
                                }
                            });
                            that.bindItemClick(carrier);

                            //$this.hide();
                        }
                        else {
                            alert(res.msg)
                        }
                    }
                });
                that.bindCreateBtn();
            })
        },
        bindItemClick: function (carrier) {
            $('button[data-for=' + carrier + ']').unbind("click").bind("click", function () {
                _t = $(this).attr("data-for");
                if ($(".pb-item").find('input[type="hidden"][value=' + $(this).attr("data-flow-id") + ']').length > 0) {
                    var p = $(".pb-item").find('input[type="hidden"][value=' + $(this).attr("data-flow-id") + ']').parent();
                    p.remove();
                } else {
                    _tpl = $("tr td[data-what='" + _t + "']").find("li[data-tpl='true']").clone();
                    _tpl.find("span").html($(this).html());
                    _tpl.find("input[type='hidden']").val($(this).attr("data-flow-id"));
                    _tpl.removeAttr("data-tpl");
                    $("tr td[data-what='" + _t + "']").append(_tpl)
                }
                $(this).toggleClass("sld");
            });
        },
        bindCreateBtn: function () {
            var that = this;
            var percentage = {"YIDONG": 0, "LIANTONG": 0, "DIANXIN": 0};
            var postParams;
            var hasPost = false;
            $(".js_create_btn").unbind('click').bind('click', function () {
                postParams = new Array();
                var _is = $(".pb-item").not(".pb-item[data-tpl='true']");
                if (_.size(_is) > 0) {
                    _.each(_is, function (el, index) {
                        if ($(el).find("input[type='hidden']").val()) {
                            var _c = $(el).attr("data-array");
                            percentage[_c] += parseInt($(el).find("input[type='text']").val());
                            postParams.push({
                                probability: $(el).find("input[type='text']").val(),
                                flow: {
                                    id: $(el).find("input[type='hidden']").val()
                                }
                            });
                        }
                    });
                    var canPost = true;
                    var _tm;
                    _.each(percentage, function (value, key) {
                        if (value != 100) {
                            if (key === "YIDONG") {
                                _tm = "移动的流量包概率总和应该为100%！";
                            } else if (key === "LIANTONG") {
                                _tm = "联通的流量包概率总和应该为100%！";
                            } else if (key === "DIANXIN") {
                                _tm = "电信的流量包概率总和应该为100%！";
                            }
                            canPost = false;
                            percentage = {"YIDONG": 0, "LIANTONG": 0, "DIANXIN": 0};
                            return;
                        }
                    });
                    if (canPost
                        && !hasPost) {
                        hasPost = true;
                        var urlApi = that.isNewAct ? 'newActivity' : 'updateActivity';
                        if (that.isNewAct) {
                            that.inputParams.description = "分享活动抢流量，快来参与吧！";
                        }
                        $.ajax({
                            url: absoluteContextPath + "/activity/" + urlApi,
                            type: 'POST',
                            dataType: 'json',
                            contentType: 'application/json',
                            data: JSON.stringify({
                                activity: that.inputParams,
                                flows: postParams
                            }),
                            beforeSend: function (request) {
                                request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
                            },
                            success: function (res) {
                                if (res.result == 0) {
                                    $("#modal-container-936389").removeClass('fade')
                                        .removeClass('hide');
                                    $("body").append($("<div class='modal-backdrop fade in'></div>"));
                                    $("#act_id_text").html(res.data.activity.link);
                                    $("#exLind_text").html(res.data.activity.exchangeLink);
                                    $(".js_close_btn").bind('click', function () {
                                        location.href = absoluteContextPath + "/activity";
                                    })
                                }
                                else {
                                    alert(res.msg)
                                }
                            }
                        });
                    }
                    else {
                        alert(_tm);
                    }
                }
            })
        }
    };

    add.init();

});

function uploadFile(fileInputId, prviewElementId, hideValueId, type) {
    var file = $("#" + fileInputId);
    var previewElement = $("#" + prviewElementId);
    var val = $("#" + hideValueId);
    if (file == null || file == undefined) {
        alert("文件选择元素ID无效！");
        return;
    }
    if (val == null && val == undefined) {
        alert("返回值存储元素ID无效！");
        return;
    }
    var gp = self.setInterval("getProgress()", 50);
    $.ajaxFileUpload(
        {
            url: absoluteContextPath + '/common/file/upload/' + type,
            type: 'post',
            fileElementId: fileInputId,
            async: false,
            success: function (data) {
                console.info("%o", data);
                data = JSON.parse($(data).find("body").html());

                window.clearInterval(gp);
                //上传成功返回的信息｛filePath:上传文件后取得的url，result:是否成功，成功为0，失败为-x｝
                if (data.result == "0") {
                    if (previewElement != null && previewElement != undefined) {
                        previewElement.attr("src", data.url);
                    }
                    if (val != null && val != undefined) {
                        val.val(data.url);
                    }
                } else {
                    alert(data.msg);
                }
                if (typeof callback == "function") {
                    callback();
                }
            },
            error: function (data, status, e) {
                alert("上传失败:" + e);
                window.clearInterval(gp);
            }
        }
    )
}

var getProgress = function () {
    $.ajax({
        url: absoluteContextPath + "/common/file/upload/progress",
        async: false,
        type: "post",
        beforeSend: function () {

        },
        success: function (data) {
            console.log("progress data:%o", data);
            if (data.result != 0) {
                return;
            }
            $(".circleProgress_wrapper ").show();
            $(".upload_progress_tip").html(data.progress != 100.00 ? data.progress + "%" : "上传成功!");
            $(".progress_text").html(data.progress.split(".")[0] + "%");
            if (data.progress <= 50) {
                var rotate = 45 + 3.6 * data.progress;
                $(".rightcircle").css("-webkit-transform", "rotate(" + rotate + "deg)");
            } else {
                $(".rightcircle").css("-webkit-transform", "rotate(225deg)");
                var rotate = 45 + (data.progress - 50) * 3.6;
                $(".leftcircle").css("-webkit-transform", "rotate(" + rotate + "deg)");
            }

            if (data.progress == 100.00) {
                setTimeout(function () {
                    $(".circleProgress_wrapper").fadeOut();
                    $(".rightcircle").css("-webkit-transform", "rotate(45deg)");
                    $(".leftcircle").css("-webkit-transform", "rotate(45deg)");
                }, 500);
            }
        },
        error: function (e) {
            console.error("get file upload occur error:%o", e);
        }
    })
}